package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.h4313.ghome.GHomeApplication;

import android.os.AsyncTask;

public class CreateModuleTask extends AsyncTask<Map<String, String>, Void, Integer> {

	public interface CreateModuleCallback {
		public void onModuleCreated(String moduleName, int id);
	}
	
	WeakReference<CreateModuleCallback> mCallback;
	String mModuleName;

	public CreateModuleTask(String moduleName, CreateModuleCallback callback) {
		mCallback = new WeakReference<CreateModuleCallback> (callback);
		mModuleName = moduleName;
	}
	
	@Override
	protected Integer doInBackground(Map<String, String>... params) {
		
		String res;
		try {
			res = ServerUtilities.put(GHomeApplication.SERVER_URL + "/modules/"+mModuleName, params[0]);
			JSONObject objRes = new JSONObject(res);
			return objRes.getInt("id");
		} catch (IOException e) {
			e.printStackTrace();
			return -1;
		} catch (JSONException e) {
			e.printStackTrace();
			return -1;
		}
		
		
	}

	@Override
	protected void onPostExecute(Integer result) {
		if (result != null && result != -1) {
			if (mCallback.get() != null) {
				mCallback.get().onModuleCreated(mModuleName, result);
			}
		}
	} 
}
